package main

import (
	"io/ioutil"
	"log"
	"os"
	"strings"

	"gopkg.in/telegram-bot-api.v4"
)

func main() {
	// Read the list of banned words from a text file
	bannedWordsFile := os.Getenv("BANNED_WORDS_FILE")
	bannedWords, err := readBannedWords(bannedWordsFile)
	if err != nil {
		log.Fatal(err)
	}

	// Create a Telegram bot client
	botToken := os.Getenv("TELEGRAM_BOT_TOKEN")
	bot, err := tgbotapi.NewBotAPI(botToken)
	if err != nil {
		log.Fatal(err)
	}

	// Set up updates to listen for
	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	// Start receiving updates from the bot
	updates, err := bot.GetUpdatesChan(u)

	// Process incoming updates
	for update := range updates {
		if update.Message == nil {
			continue
		}

		// Check for group or supergroup messages only
		if update.Message.Chat.Type != "group" && update.Message.Chat.Type != "supergroup" {
			continue
		}

		// Check if the message contains any banned words
		if containsBannedWords(update.Message.Text, bannedWords) {
			// Kick the user
			kickConfig := tgbotapi.KickChatMemberConfig{
				ChatMemberConfig: tgbotapi.ChatMemberConfig{
					ChatID: update.Message.Chat.ID,
					UserID: update.Message.From.ID,
				},
			}
			_, err := bot.KickChatMember(kickConfig)
			if err != nil {
				log.Println("Failed to kick user:", err)
			}

			// Delete the message
			deleteConfig := tgbotapi.DeleteMessageConfig{
				ChatID:    update.Message.Chat.ID,
				MessageID: update.Message.MessageID,
			}
			_, err = bot.DeleteMessage(deleteConfig)
			if err != nil {
				log.Println("Failed to delete message:", err)
			}
		}
	}
}

// Read the list of banned words from a text file
func readBannedWords(filename string) ([]string, error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	words := strings.Split(string(content), "\n")
	return words, nil
}

// Check if the message contains any banned words
func containsBannedWords(text string, bannedWords []string) bool {
	for _, word := range bannedWords {
		if strings.Contains(text, word) {
			return true
		}
	}
	return false
}